package com.sds.sweng.swat.miplatform.service.editors;


import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.io.XPP3Reader;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.part.MultiPageEditorPart;

import com.sds.sweng.swat.miplatform.service.pages.MiplatformServicePage;

public class MiplatformServiceEditor extends MultiPageEditorPart implements IResourceChangeListener{

	private MiplatformServicePage miplatformServicePage;
	/** The text editor used in page 0. */
	private MiplatformSourceEditor editor;

	private int SERVICE_PAGE;
	private int SOURCE_PAGE;

	private String sourceText;
	private Document sourceXml;

	private int selectedPage;
	private boolean sourceChanged;

	/**
	 * Creates a multi-page editor example.
	 */
	public MiplatformServiceEditor() {
		super();
		ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
	}

	/**
	 * Create Miplatform Service Editor Page
	 */
	void createServicePage() {
		miplatformServicePage = new MiplatformServicePage(getContainer(), this);
		SERVICE_PAGE = addPage(miplatformServicePage);
		setPageText(SERVICE_PAGE, "Service");
	}

	/**
	 * Create Miplatform XML Source Page (Plain Text)
	 */
	void createSourcePage() {
		try {
			editor = new MiplatformSourceEditor();
			SOURCE_PAGE = addPage(editor, getEditorInput());
			setPageText(SOURCE_PAGE, "Source");
			setTitle(editor.getTitle());

			sourceText = editor.getDocumentProvider().getDocument(editor.getEditorInput()).get();
			sourceText = StringUtils.replace(sourceText, "&#32;", " ");

			try {
				XPP3Reader xmlReader = new XPP3Reader();
				sourceXml = xmlReader.read(sourceText.toCharArray());
			} catch (Exception e) {
				throw new RuntimeException(e);
			}

			miplatformServicePage.setSourceXml(sourceXml);
		} catch (PartInitException e) {
			ErrorDialog.openError(
				getSite().getShell(),
				"Error creating nested text editor",
				null,
				e.getStatus());
		}
	}

	public void replaceSource() {
		editor.getDocumentProvider().getDocument(editor.getEditorInput()).set(sourceXml.asXML());
	}

	/**
	 * Creates the pages of the multi-page editor.
	 */
	protected void createPages() {
		createServicePage();
		createSourcePage();

		selectedPage = SOURCE_PAGE;
	}
	/**
	 * The <code>MultiPageEditorPart</code> implementation of this
	 * <code>IWorkbenchPart</code> method disposes all nested editors.
	 * Subclasses may extend.
	 */
	public void dispose() {
		ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
		super.dispose();
	}
	/**
	 * Saves the multi-page editor's document.
	 */
	public void doSave(IProgressMonitor monitor) {
		getEditor(SOURCE_PAGE).doSave(monitor);
	}
	/**
	 * Saves the multi-page editor's document as another file.
	 * Also updates the text for page 0's tab, and updates this multi-page editor's input
	 * to correspond to the nested editor's.
	 */
	public void doSaveAs() {
		IEditorPart editor = getEditor(SOURCE_PAGE);
		editor.doSaveAs();
		setTitle(editor.getTitle());
		setInput(editor.getEditorInput());
	}
	/**
	 * The <code>MultiPageEditorExample</code> implementation of this method
	 * checks that the input is an instance of <code>IFileEditorInput</code>.
	 */
	public void init(IEditorSite site, IEditorInput editorInput)
		throws PartInitException {
		if (!(editorInput instanceof IFileEditorInput))
			throw new PartInitException("Invalid Input: Must be IFileEditorInput");
		super.init(site, editorInput);
	}
	/* (non-Javadoc)
	 * Method declared on IEditorPart.
	 */
	public boolean isSaveAsAllowed() {
		return true;
	}

	protected void pageChange(int newPageIndex) {
		super.pageChange(newPageIndex);
		selectedPage = newPageIndex;
	}
	/**
	 * Closes all project files on project close.
	 */
	public void resourceChanged(final IResourceChangeEvent event){
		switch (event.getType()) {
			case IResourceChangeEvent.PRE_CLOSE:
				Display.getDefault().asyncExec(new Runnable(){
					public void run(){
						IWorkbenchPage[] pages = getSite().getWorkbenchWindow().getPages();
						for (int i = 0; i<pages.length; i++){
							if(((FileEditorInput)editor.getEditorInput()).getFile().getProject().equals(event.getResource())){
								IEditorPart editorPart = pages[i].findEditor(editor.getEditorInput());
								pages[i].closeEditor(editorPart,true);
							}
						}
					}
				});
				break;
			case IResourceChangeEvent.POST_CHANGE:
				break;
			default:
				break;
		}
	}

}
